<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\UploadFileEvent;
use App\Models\V1\ExcellentStudents;
use App\Models\V1\ExcellentTeachers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;
use Log;

class ImageUploadController extends Controller
{


    /**
     * 上传更新用户头像
     *
     * @param Request $request
     */
    public function uploadAvatar(Request $request)
    {

        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '上传头像失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'avatar/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '上传头像成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];
                } else {
                    $response['msg'] = '上传头像失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }


    /**
     * 上传名师风采／优秀学生配图
     *
     * @param Request $request
     * @return $this
     */
    public function uploadExcellentAvatar(Request $request)
    {
        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '[' . $loginUser['code'] . '],上传配图失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'excellent/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '[' . $loginUser['code'] . '],上传配图成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];

                    // 上传新闻配图成功，触发事件
                    event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['data']));
                } else {
                    $response['msg'] = '管理员[' . $loginUser['code'] . '],上传配图失败，服务端目录检查失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }

    /**
     * 上传公告配图
     *
     * @param Request $request
     * @return $this
     */
    public function uploadNoticeImage(Request $request)
    {
        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '[' . $loginUser['code'] . '],上传新闻配图失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'notices/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '[' . $loginUser['code'] . '],上传新闻配图成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];

                    // 上传新闻配图成功，触发事件
                    event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['data']));
                } else {
                    $response['msg'] = '管理员[' . $loginUser['code'] . '],上传公告配图失败，服务端目录检查失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }

    /**
     * 上传公告配图
     *
     * @param Request $request
     * @return $this
     */
    public function uploadScrollImage(Request $request)
    {
        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '[' . $loginUser['code'] . '],上传滚动图片失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'scroll/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '[' . $loginUser['code'] . '],上传滚动图片成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];

                    // 上传新闻配图成功，触发事件
                    event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['data']));
                } else {
                    $response['msg'] = '管理员[' . $loginUser['code'] . '],上传滚动图片失败，服务端目录检查失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }


    /***
     * 上传校服图片
     * @param Request $request
     * @return $this
     */
    public function uploadClothImage(Request $request)
    {
        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '[' . $loginUser['code'] . '],上传校服图片失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'cloth/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '[' . $loginUser['code'] . '],上传校服图片成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];

                    // 上传校服成功，触发事件
                    event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['data']));
                } else {
                    $response['msg'] = '管理员[' . $loginUser['code'] . '],上传校服图片失败，服务端目录检查失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }


    /***
     * 上传新生头像
     * @param Request $request
     * @return $this
     */
    public function uploadNewStuAvatar(Request $request)
    {
        $loginUser = Auth::user();

        // 返回参数数组
        $response = [
            'code' => -1, // 0: 成功; 其余失败
            'msg' => '[' . $loginUser['code'] . '],上传新生头像失败！',
            'data' => [
                'src' => '',
                'title' => '图片名称',
            ],
        ];
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'newstudent/';
            $storagePath .= $loginUser['code'];

            // 获取request中上传文件对象
            $file = $request->file('file');

            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['msg'] = '图片文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);

                if ($success) {
                    $response['code'] = 0;
                    $response['msg'] = '[' . $loginUser['code'] . '],上传新生头像成功！';
                    $response['data'] = [
                        'src' => asset('storage' . '/' . $originPath),
                        'title' => $originPath,
                    ];

                    // 上传校服成功，触发事件
                    event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['data']));
                } else {
                    $response['msg'] = '管理员[' . $loginUser['code'] . '],上传新生头像失败，服务端目录检查失败！';
                }
            }
        }
        return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
    }





    ///////////////////////////////////////////////////////////////////
    /// 功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 验证文件是否上传成功
     *
     * @param $url
     * @return bool
     */
    protected function checkFile($url)
    {
        // 验证文件已存在
        $exists = Storage::disk('public')->exists($url);
        if ($exists) {
            return true;
        }
        return false;
    }

    /**
     * 验证文件类型是否合法
     *
     * @param $objFile 文件对象
     * @return bool
     */
    protected function validFile($objFile)
    {
        // 合法文件类型
        $fileTypes = array('png', 'jpg', 'jpeg');
        if (in_array($objFile->getClientOriginalExtension(), $fileTypes)) {
            return true;
        }
        return false;
    }

    /**
     * 数据库更新头像路径
     *
     * @param $flag
     * @param $code
     * @param $originPath
     * @return bool
     */
    private function handleProfile($flag, $code, $originPath)
    {
        // 头像原图路径
        $data = [
            'avatar' => $originPath,
        ];
        Log::info($data);
        if ($flag) {
            $rspObj = ExcellentTeachers::where('code', $code)->update($data);
        } else {
            $rspObj = ExcellentStudents::where('code', $code)->update($data);
        }
        return $rspObj;
    }


}
